<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1200px">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-suffix="："
      label-width="100px"
    >
      <el-row v-for="(item, idx) in formData.configInfoList" :key="item.key" :gutter="10">
        <el-col :span="5">
          <el-form-item label="类型" prop="type">
            <el-select
              v-model="item.type"
              placeholder="请选择配置项类型"
              @change="typeChangeHandler(item)"
            >
              <el-option :value="0" label="字符串" />
              <el-option :value="1" label="单张图片" />
              <el-option :value="2" label="多图" />
              <el-option :value="3" label="文件" />
              <el-option :value="4" label="文本域" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="标识" prop="key">
            <el-input v-model="item.key" placeholder="请输入配置项标识" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="配置项值" prop="value">
            <el-input v-if="item.type === 0" v-model="item.value" placeholder="请输入配置项值" />
            <UploadImg v-if="item.type === 1" v-model="item.value" />
            <UploadImgs v-if="item.type === 2" v-model="item.value" />
            <UploadFile v-if="item.type === 3" v-model="item.value" />
            <el-input
              v-if="item.type === 4"
              type="textarea"
              v-model="item.value"
              placeholder="请输入配置项值"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button circle type="danger" @click="removeItem(idx)">
            <Icon icon="ep:minus" />
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="success" @click="addItem">
        <Icon icon="ep:plus" />
        新增配置项
      </el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">提 交</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { AppSiteApi, AppSiteConfigItem, AppSiteVO } from '@/api/cms/appsite'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('站点配置') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  configInfoList: [] as Array<AppSiteConfigItem>
})
const formRef = ref() // 表单 Ref
const formRules = ref({})

const typeChangeHandler = (item: AppSiteConfigItem) => {
  console.log(item)
  if (item.type === 2 || item.type === 3) {
    item.value = []
  } else {
    item.value = ''
  }
}
const addItem = () => {
  formData.value.configInfoList.push({
    key: '',
    type: 0,
    value: ''
  })
}

const removeItem = (idx: number) => {
  formData.value.configInfoList.splice(idx, 1)
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let existData = await AppSiteApi.getAppSite(id)
      dialogTitle.value = existData.appName + ' - 站点配置'
      if (!existData.configInfoList) {
        existData.configInfoList = []
      }
      formData.value = existData
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AppSiteVO
    if (formType.value === 'create') {
      await AppSiteApi.createAppSite(data)
      message.success(t('common.createSuccess'))
    } else {
      await AppSiteApi.updateAppSite(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    configInfoList: []
  }
  formRef.value?.resetFields()
}
</script>
